﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace PicBagDownloader
{
    public partial class Form1 : Form
    {
        string DownloadPath = Config.Default.DownPath;
        public Form1()
        {
            InitializeComponent();
            
            
        }
        /// <summary>
        /// Save a binary file to disk.
        /// </summary>
        /// <param name="response">The response used to save the file</param>
        /// 将二进制文件保存到磁盘
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }
        /// <summary>
        /// 下载照片
        /// </summary>
        /// <param name="PageURL">照片页地址</param>
        /// <param name="FileName">照片名称</param>
        private void DownLoad(string PageURL, string FileName, string cookieStr)
        {
            CookieContainer myCookie = new CookieContainer();
            //string cookieStr = webBrowser1.Document.Cookie;
            string[] cookstr = cookieStr.Split(';');
            foreach (string str in cookstr)
            {
                string[] cookieNameValue = str.Split('=');
                Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                ck.Domain = "www.renren.com";
                myCookie.Add(ck);
            }
            //访问照片页，找到下载地址
            HttpWebRequest hreq = (HttpWebRequest)HttpWebRequest.Create(PageURL);
            hreq.Method = "GET";
            hreq.ContentType = "application/x-www-form-urlencoded";

            //自己创建的CookieContainer
            hreq.CookieContainer = myCookie;
            HttpWebResponse hres = (HttpWebResponse)hreq.GetResponse();
            //得到数据流
            Stream streamReceive = hres.GetResponseStream();

            //对获取到的数据流进行编码解析，让我们可以进行正常读取
            Encoding encoding = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(streamReceive, encoding);

            //读取出数据流中的信息
            string strResult = streamReader.ReadToEnd();

            //关闭流

            streamReader.Close();

            //关闭网络响应流

            hres.Close();
            //下面分析文档结构
            //校内的程序员用JS加载，关键是取得大图的标记：p_large
            int FlagIndex = strResult.IndexOf("p_large");
            ///找得到的话，开始分析URL地址
            if (FlagIndex != 1)
            {
                int startIndex = strResult.Substring(0, FlagIndex + 1).LastIndexOf(@"http:\/\/");
                int EndIndex = strResult.Substring(startIndex).IndexOf('"');
                string URLStr = "";
                URLStr += strResult.Substring(startIndex, EndIndex);
                string RealPicUrl = URLStr.Replace(@"\/", @"/");

                //得到正确的地址后将照片下载到本地
                WebResponse response = null;
                Stream stream = null;
                //构造照片名称
                FileName += Path.GetExtension(RealPicUrl);
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RealPicUrl);
                    request.Method = "GET";
                    //request.CookieContainer = myCookie;
                    response = request.GetResponse();
                    stream = response.GetResponseStream();
                    if (!response.ContentType.ToLower().StartsWith("text/"))
                    {
                        SaveBinaryFile(response, FileName);
                    }
                }
                catch (Exception err)
                {
                }
            }
        }
        /// <summary>
        /// 进行后台作业
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            HtmlDocument dom = (HtmlDocument)e.Argument;
            string Cookie = dom.Cookie;
            HtmlElementCollection imgliColl = dom.GetElementById("content").Children[2].Children[3].FirstChild.Children;
            for (int i = 0; i < imgliColl.Count; i++)
            {
                string imgUrl = imgliColl[i].FirstChild.FirstChild.GetAttribute("href");
                DownLoad(imgUrl, DownloadPath + i.ToString(), Cookie);
                backgroundWorker1.ReportProgress((i*100) / imgliColl.Count);
            }
        }
        /// <summary>
        /// 完成提醒
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar1.Value = 0;
            MessageBox.Show("下载完成！");            
        }
        /// <summary>
        /// 进度提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }
        /// <summary>
        /// URL转向
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Go2TbxURL();
        }
        /// <summary>
        /// 转向URL文本框中的地址
        /// </summary>
        private void Go2TbxURL()
        {
            string url = tbxURL.Text;
            if (!url.StartsWith(@"https://")) url = @"https://" + url;
            webBrowser1.Navigate(url);
        }
        /// <summary>
        /// 图片按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
        }
        /// <summary>
        /// 自动转向
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbxURL_KeyDown(object sender, KeyEventArgs e)
        {
            ///按下Enter键发生
            if ((int)e.KeyCode == 13)
            {
                //e.SuppressKeyPress = true;
                Go2TbxURL();
            }
        }
        /// <summary>
        /// 设置存储地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox5_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "选择你要存放的路径！";
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                Config.Default.DownPath = folderBrowserDialog1.SelectedPath;
                Config.Default.Save();
            }
        }
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                MessageBox.Show("请等待当前任务完成后添加新任务！");
                return;
            }
            if (DownloadPath == "")
            {
                MessageBox.Show("请先设置存放地址！");
                return;
            }
            if (!Directory.Exists(DownloadPath))
            {
                Directory.CreateDirectory(DownloadPath);
            }
            if (webBrowser1.Url.ToString().Contains("http://photo.renren.com/"))
                //启动后台线程
                backgroundWorker1.RunWorkerAsync(webBrowser1.Document);
            else MessageBox.Show("当前页面不是人人网相册页面！");
        }
    }
}
